package com.yld.car.market;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.yld.car.adapter.ImageAdapter;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.Car;
import com.yld.car.view.CircleFlowIndicator;
import com.yld.car.view.ViewFlow;
import com.yld.car.view.XListView.IXListViewListener;

/**
 * 
 * 首页，负责所有汽车的类型显示，广告等处理。
 * 
 * @author apple
 * 
 */

public class FindFilterCarTypeActivity extends BaseActivity implements
		OnItemClickListener, IXListViewListener {

	private SharedPreferences settings;
	private SharedPreferences.Editor mEditor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.find_car_type);
		// 设置布局
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView) findViewById(R.id.title)).setText("选择品牌");
		showBackButton();
		allCarLists = (ListView) findViewById(R.id.typeCarLists);
		// searchImageView = (ImageView) findViewById(R.id.searchImage);

		// frameLayout = (FrameLayout) findViewById(R.id.framelayout);
		settings = this.getSharedPreferences("update_data", MODE_PRIVATE);
		mEditor = settings.edit();
		// initFlowImageViews();
		// searchImageView.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// Intent intent = new Intent();
		// intent.setClass(FindFilterCarTypeActivity.this,
		// CarKeyWordActivity.class);
		// startActivity(intent);
		//
		// }
		// });
		allCarLists.setOnItemClickListener(this);
//		allCarLists.setXListViewListener(this);
//		allCarLists.setPullLoadEnable(true);
//		allCarLists.setPullRefreshEnable(true);
		utils = NetworkProgressUtils.getInstance();
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		new GetCarTypeTask().execute("");
		mHandler = new Handler();

	}

	// private FrameLayout frameLayout;
	private ViewFlow viewFlow;

	private void initFlowImageViews() {
		viewFlow = (ViewFlow) findViewById(R.id.viewflow);
		viewFlow.setAdapter(new ImageAdapter(this, urls));
		viewFlow.setmSideBuffer(urls.length); // 实际图片张数， 我的ImageAdapter实际图片张数为3

		CircleFlowIndicator indic = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
		viewFlow.setFlowIndicator(indic);
		viewFlow.setTimeSpan(2000);
		viewFlow.setSelection(3 * 1000); // 设置初始位置
		viewFlow.startAutoFlowTimer(); // 启动自动播放
	}

	private String[] urls = {
			"http://c.hiphotos.baidu.com/image/pic/item/5243fbf2b211931312c50bae67380cd791238d2e.jpg",
			"http://d.hiphotos.baidu.com/image/pic/item/58ee3d6d55fbb2fb9835341f4d4a20a44623dca5.jpg",
			"http://g.hiphotos.baidu.com/image/pic/item/c995d143ad4bd1138d126f3258afa40f4afb05d7.jpg",
			"http://a.hiphotos.baidu.com/image/pic/item/472309f790529822c2d580cbd5ca7bcb0b46d4d0.jpg" };

	private ImageView searchImageView;
	private Handler mHandler = null;
	private ListView allCarLists = null;
	private int start = 0;
	private static int refreshCnt = 0;
	private ProgressBar mBar;

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		if (adapterView.getAdapter().getItem(position) == null) {
			return;
		}
		Car c = (Car) adapterView.getAdapter().getItem(position);

		String cId = c.getId();

		Intent intent = new Intent();
		intent.putExtra("cId", cId);
		intent.setClass(this, CarSeriesActivity.class);
		startActivity(intent);
		finish();
	}

	private NetworkProgressUtils utils = null;
	private ArrayList<Car> all;

	private class GetCarTypeTask extends
			AsyncTask<String, String, ArrayList<Car>> {

		@Override
		protected ArrayList<Car> doInBackground(String... params) {

			publishProgress("");
			if (utils.getAPNType(getApplicationContext()) == -1) {

				return null;
			} else {

				Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
						ConstantUtils.ALL_METHROD_NAME.get(0),
						ConstantUtils.NAME_SPACE
								+ ConstantUtils.ALL_METHROD_NAME.get(0),
						ConstantUtils.GET_BRAND_URL, null);
				// System.out.println(o + "09090909");

				all = utils.parseJson(o.toString(), "table",
						NetworkProgressUtils.BASE_CAR_TYPE,false);

				// System.out.println("all====" + all);
				// System.out.println("o=====" + o);
				// ArrayList<Car> c = utils.parseJson(o.toString(), "table",
				// NetworkProgressUtils.SEARCH_CAR_TYPE);
				// System.out.println("all:" + c);
				return all;
			}

		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);

		}

		@Override
		protected void onPreExecute() {
			mBar.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			if (result == null) {

				Toast.makeText(getApplicationContext(), "网络未连接，请设置网络!",
						Toast.LENGTH_SHORT).show();
			} else {
				if (result.size() > 0) {
//					ArrayList<Car> partOne = new ArrayList<Car>(5);
//
//					Car c[] = new Car[6];
//
//					System.arraycopy(result.toArray(), 0, c, 0, c.length);
//
//					l = new ArrayList(Arrays.asList(c));
					// System.out.println(l);
					mAdapter = new CarTypeAdapter(result);
					allCarLists.setAdapter(mAdapter);
				} else {
					Toast.makeText(getApplicationContext(),
							"无法从服务器读取数据，建议您检查当前网络环境！!", Toast.LENGTH_SHORT)
							.show();
				}

			}

		}

	}

	List<Car> l = null;

	private class CarTypeAdapter extends BaseAdapter {

		private List<Car> all = null;

		private CarTypeAdapter(List<Car> all) {
			this.all = all;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return all.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return all.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.my_item_car, null);
			}

			TextView t1 = (TextView) convertView.findViewById(R.id.itemTitle);
			// t1.setTextSize(22);
			t1.setTextColor(getResources().getColor(R.color.black_light));
			t1.setText(all.get(position).getName());

			// TextView t2 = (TextView)
			// convertView.findViewById(R.id.itemContent);
			// t2.setText(all.get(position).getName());
			return convertView;
		}

	}

	private void getItems() {

		if (all != null && l != null) {

			// for(int i=0;i<2;i++){

			int size2 = all.size();

			for (int i = 0; i < 3; i++) {
				int size1 = l.size();
				if (size1 < size2) {
					l.add(all.get(size1));
				} else {
					Toast.makeText(this, "暂无更新数据", Toast.LENGTH_SHORT).show();
					break;
				}

			}

		}

	}

//	private void onLoad() {
//		allCarLists.stopRefresh();
//		allCarLists.stopLoadMore();
//		long lastUpdateTime = settings.getLong("lastTime",
//				System.currentTimeMillis());
//
//		long currentTime = System.currentTimeMillis();
//
//		long calTime = (currentTime - lastUpdateTime);
//
//		String displayContent = "";
//		if (calTime <= 60000) {
//			displayContent = "刚刚";
//
//		} else {
//
//		}
//
//		allCarLists.setRefreshTime("刚刚");
//	}

	@Override
	public void onRefresh() {

		// System.out.println("onRefresh====>");
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				start = ++refreshCnt;
				// all.clear();
				getItems();
				// mAdapter.notifyDataSetChanged();
				// if (all != null) {
				// mAdapter = new CarTypeAdapter(all);
				// allCarLists.setAdapter(mAdapter);
				// }

				if (mAdapter != null) {
					mAdapter.notifyDataSetChanged();
				}
				//onLoad();
			}
		}, 2000);
	}

	CarTypeAdapter mAdapter = null;

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				// System.out.println("onLoadMore=======>");
				getItems();
				if (mAdapter != null) {
					mAdapter.notifyDataSetChanged();
				}
				//onLoad();
			}
		}, 2000);
	}
	
	
}
